﻿#region Creditos

/* Autor: Edilberto Sánchez Forero	*/
/* Email: esanchezfo@gmail.com		*/
/* Licencia: Propietario			*/
/* País: Colombia, Bogotá			*/

#endregion

#region Librerias

using System.Collections.Generic;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;

using ESF.SSO.Web.Tools.Modules;
using ESF.Web;
using ESF.SSO.Core.Entities;
using ESF.Web.Pages;
using ESF.General.Entity;
using ESF.SSO.Core.Entities.BasicReferences;
using ESF.General;
using ESF.SSO.Web.Tools.Presenter;

#endregion


namespace ESF.SSO.Web.Tools.ServerControls
{
	[AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand, 
        Level = AspNetHostingPermissionLevel.Minimal),
	ToolboxData ("<{0}:UserMenu runat=\"server\"></{0}:UserMenu>")]
	public class UserMenu : BaseServerControl<UserMenuPresenter>, IUserMenuViewer
	{
		#region Propiedades

		public string LinkTarget
		{
			set
			{
				ViewState ["LinkTarget"] = value;
			}
			get
			{
				if (ViewState ["LinkTarget"] == null)
				{
					return AuthenticationModule.LinkTarget;
				}

				return ViewState ["LinkTarget"] as string;
			}
		}

		#endregion
		

		#region Render

		protected override void Render (HtmlTextWriter pWriter)
		{
			List<UserMenuItem> items;
			

			Page.Trace.Write (string.Format ("UserMenu Render Start {0} {1}", frmUserAlias, frmIsAuthenticated));
		
			_Presenter = new UserMenuPresenter (this);
		
			_Presenter.Load ();
			
			items = UserMenuItems;
			
			if (DataHelper.IsEmpty (items))
			{
				if (frmIsAuthenticated)
				{
					JS.AddWarning (Page, string.Format ("Su usuario {0} no tiene menu asignado para la aplicación {1} ({2}), consulte con su administrador", frmUserAlias, frmApplicationName, frmApplicationCode));
				}
				else
				{
					JS.AddWarning(Page, string.Format ("No hay un menu asignado para la aplicación {0} ({1}), consulte con su administrador", frmApplicationName, frmApplicationCode));
				}
			}
			else
			{
					pWriter.AddAttribute (HtmlTextWriterAttribute.Id, ClientID);
					pWriter.AddAttribute (HtmlTextWriterAttribute.Class, (string.IsNullOrEmpty (CssClass) ? "userMenu" : CssClass) + " " + frmApplicationCode.Replace ('.', '_'));
				
				pWriter.RenderBeginTag (HtmlTextWriterTag.Div);
				
					RenderUserMenu (pWriter, null, items.FindAll (um => um.Parent == null), items, 1);
				
				pWriter.RenderEndTag ();
			}

			Page.Trace.Write("UserMenu Render End");
		}
		
		
		private void RenderUserMenu (HtmlTextWriter pWriter, UserMenuItem pParentItem, List<UserMenuItem> pItems, List<UserMenuItem> pAllItems, int pLevel)
		{
			List<UserMenuItem> children;

		
			if (DataHelper.IsEmpty (pItems)) { return; }
		
				pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "level_" + pLevel);
				
				if (pParentItem != null)
				{
					pWriter.AddAttribute (HtmlTextWriterAttribute.Style, "display:none;");
					pWriter.AddAttribute (HtmlTextWriterAttribute.Id, ClientID + "_" + pParentItem.ID);
				}

			pWriter.RenderBeginTag(HtmlTextWriterTag.Ul);

			foreach (UserMenuItem item in pItems)
			{
				children = pAllItems.FindAll(um => um.Parent != null && um.Parent.Equals(item));

					pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "level_" + pLevel);
				pWriter.RenderBeginTag(HtmlTextWriterTag.Li);

				if (string.IsNullOrWhiteSpace (item.URL))
				{
					pWriter.AddAttribute(HtmlTextWriterAttribute.Onclick, "$('#" + ClientID + "_" + item.ID + "').toggle();");
				}
				else
				{
					if (item.URL.StartsWith("javascript", System.StringComparison.InvariantCultureIgnoreCase))
					{
						pWriter.AddAttribute(HtmlTextWriterAttribute.Href, "#");

						pWriter.AddAttribute (HtmlTextWriterAttribute.Onclick, item.URL + "; $('#" + ClientID + "_" + item.ID + "').toggle();");
					}
					else
					{
						pWriter.AddAttribute (HtmlTextWriterAttribute.Target, LinkTarget);
						pWriter.AddAttribute(HtmlTextWriterAttribute.Href, RequestHelper.AppendVarValueToHTTPURL(item.URL, "ApplicationCode", frmApplicationCode, "frmTitle", TextHelper.EncryptRSA(item.Name)));
					}
				}

				if (!TextHelper.IsEmpty(item.Description))
				{
					pWriter.AddAttribute(HtmlTextWriterAttribute.Title, item.Description);
				}

				pWriter.RenderBeginTag(HtmlTextWriterTag.A);

				pWriter.RenderBeginTag(HtmlTextWriterTag.Div);
					pWriter.Write(item.Name);
				pWriter.RenderEndTag();

				if (children.Count > 0)
				{
						pWriter.AddAttribute(HtmlTextWriterAttribute.Class, "arrow");
						pWriter.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(GetType(), "ESF.SSO.Web.Tools.ServerControls.Images.Icons.BulletArrowDown_10x10.gif"));
					pWriter.RenderBeginTag(HtmlTextWriterTag.Img);
					pWriter.RenderEndTag();
				}

				pWriter.RenderEndTag();

				RenderUserMenu(pWriter, item, children, pAllItems, pLevel + 1);

				pWriter.RenderEndTag();
			}

			pWriter.RenderEndTag();
		}
		
		#endregion
		
		
		#region Miembros de IUserMenu

		public List<UserMenuItem> UserMenuItems
		{
			get 
			{
				return AuthenticationModule.UserMenuItems; 
			}
		}
		
		
		public User SignedInUser
		{
			set { AuthenticationModule.SignedInUser = value; }
			get { return AuthenticationModule.SignedInUser; }
		}

		#endregion
	}
}
